package cn.cgg.synchronization;

import cn.cgg.Constants;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import javax.swing.*;
import java.io.UnsupportedEncodingException;
import java.util.List;

public class Consumer {
    public static void main(String[] args) throws Exception {
        //创建消费者组
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("hello-world");
        //设置nameserver地址
        consumer.setNamesrvAddr(Constants.NAME_SERVER_URL);
        //订阅topic 指定tag标签
        consumer.subscribe("log-topic","info_tag");
        //注册消息监听器
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                //%s 字符串输出  %d 整数输出  %f浮点输出  %n换行  Thread.currentThread().getName() 应为字符串否则报错
                System.out.printf("%s 接收到的消息: %n",Thread.currentThread().getName());
                msgs.stream().forEach(messageExt -> {
                    String body = null;
                    try {
                        body = new String(messageExt.getBody(), RemotingHelper.DEFAULT_CHARSET);
                    } catch (UnsupportedEncodingException e){
                        e.printStackTrace();
                    }
                    System.out.println(body);
                });
                //消费失 败  稍后尝试消费  将进行多次尝试 (失败次数越多 时间间隔越长) RECONSUME_LATER
                //return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;//消费成功
            }
        });
        //启动消费者
        consumer.start();
        System.out.println("消费者启动");
    }

}
